package com.example.asus.handlerthread;

import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class HandlerThreadActivity extends AppCompatActivity {
    private Button startButton=null;
    private Button endButton=null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_handler_thread);
        startButton=(Button)findViewById(R.id.startButton);
        startButton.setOnClickListener(new StartButtonListener());
        endButton=(Button)findViewById(R.id.endButton);
        endButton.setOnClickListener(new EndButtonListener());
    }
    //创建一个Handler对象
    Handler handler=new Handler();

    class StartButtonListener implements View.OnClickListener{
        @Override
        public void onClick(View v) {
            handler.post(updateThread);//将线程对象updateThread添加到队列中
        }
    }

    class EndButtonListener implements View.OnClickListener{
        @Override
        public void onClick(View v) {
            handler.removeCallbacks(updateThread);
        }
    }
    //将要执行的操作写在线程对象的run方法中
    Runnable updateThread=new Runnable() {
        @Override
        public void run() {
            System.out.println("UpdateThread");//打印指定信息
            Log.v("tag","UpdateThread");//打印日志
            handler.postDelayed(updateThread,2000);//执行postDelayed延时两秒
        }
    };
}
